package com.study.testShiro.service.impl;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import com.study.testShiro.service.ILoginService;
import com.study.testShiro.utils.ReturnMsg;

import cn.hutool.core.util.StrUtil;

@Service
public class LoginServiceImpl implements ILoginService {

	@Override
	public ReturnMsg login(String username, String password) {
		if(StrUtil.hasEmpty(username,password)) {
			return ReturnMsg.fail("用户名密码不能为空");
		}
		// 1、获取Subject实例对象
        Subject currentUser = SecurityUtils.getSubject();

        // 2、将用户名和密码封装到UsernamePasswordToken
        UsernamePasswordToken token = new UsernamePasswordToken(username, password,true);

        // 3、认证
        String msg = "";
        try {
            currentUser.login(token);// 传到MyAuthorizingRealm类中的方法进行认证
            Session session = currentUser.getSession();
            session.setAttribute("userName", username);
            //返回登录成功消息
            return ReturnMsg.success("登录成功");
        }catch (UnknownAccountException e)
        {
            e.printStackTrace();
            msg = "UnknownAccountException -- > 账号不存在：";
        }
        catch (IncorrectCredentialsException e)
        {
            msg = "IncorrectCredentialsException -- > 密码不正确：";
        }
        catch (AuthenticationException e) {
            e.printStackTrace();
            msg="用户验证失败";
        }

		return ReturnMsg.fail(msg);
	}

	@Override
	public void logout() {
		// 1、获取Subject实例对象
        Subject currentUser = SecurityUtils.getSubject();
        currentUser.logout();
	}
}
